If-then statements.
If condition, do something.
if (condition) { do something; }
if ( x > 4 ) { alert("Hey kids, x is greater than 4!"); }
Have a look at this...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function Hello() { x = 6; if ( x > 4) { alert("Hey kids, x is greater than 4!"); } } //--></SCRIPT> </HEAD> <BODY> <A HREF="javascript:Hello()">Click here</A> </BODY> </HTML> |
Understand what's going on? Good. I thought so. An if-then statement is pretty simple to grasp. It is also one of the most powerful tools in your bag of tricks. This simple statement (and its variations) are the brains behind your programs. This is the computer making a decision.
Exercise: Add a prompt box to the above page. When you click on a link, it asks the user for a number. If that number is greater than 4, you get an alert box saying something like "Hey kids, 8 is greater than 4!".
Adding to the if statement is the if-else statement...
If condition, do something...
Else, do something else.
if (condition) { do something; } else { do something else; }
if ( x > 4 ) { alert("Hey kids, x is greater than 4!"); } else { alert("Hey kids, x is NOT greater than 4!"); }
Our example again. This time we'll make x = 3.
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function Hello() { x = 3; if ( x > 4) { alert("Hey kids, x is greater than 4!"); } else { alert("Hey kids, x is NOT greater than 4!"); } } //--></SCRIPT> </HEAD> <BODY> <A HREF="javascript:Hello()">Click here</A> </BODY> </HTML> |
Exercise: You guessed it. Add that feature to your last exercise.
<< BACK NEXT >> |
Javascript Reference irt.org/Javascript FAQ Deja Power Search Joke Break |
Print version available - Get the PageTutor book & CD |
|
|